package utils

import (
	"crypto/sha1"
	"encoding/hex"
	"math/rand"
	"regexp"
	"strings"
	"time"
)

// IsValid 校验手机号
func IsValid(telephone string) bool {
	regular := "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$"
	compile, err := regexp.Compile(regular)
	if err != nil {
		return false
	}
	if match := compile.MatchString(telephone); !match {
		return false
	}
	return true
}

// GenPassword 生成密码
// salt:sha1(pwd+salt)
func GenPassword(pwd, salt string) string {
	hash := sha1.New()
	hash.Write([]byte(pwd + salt))

	return salt + ":" + hex.EncodeToString(hash.Sum(nil))
}

// CheckPassword 校验密码是否正确
func CheckPassword(pwd, realPwd string) bool {
	saltPwd := strings.Split(realPwd, ":")
	if len(saltPwd) == 0 {
		return false
	}
	shouldBe := GenPassword(pwd, saltPwd[0])
	if realPwd != shouldBe {
		return false
	}
	return true
}

// GenDefaultNick 生成默认昵称
func GenDefaultNick() string {
	alpha := []rune("abcdefghijklmnopqrstuvwxyz")
	defaultNick := make([]rune, 10)
	r := rand.New(rand.NewSource(time.Now().Unix()))
	for i := range defaultNick {
		defaultNick[i] = alpha[r.Intn(len(alpha))]
	}
	return string(defaultNick)
}
